using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using ThridGroup.ERP.Application.ProductionSystem;
using ThridGroup.ERP.ProductionSystem;
using ThridGroup.ERP.DTO;

namespace ThridGroup.ERP.Web.Areas.ProductionSystem.Controllers
{
    [Area("ProductionSystem")]
    [Route("ProductionSystem/[controller]")]
    public class WorkshopController : AbpController
    {
        private readonly IWorkshopService _workshopService;
        private readonly ILogger<WorkshopController> _logger;

        public WorkshopController(
            IWorkshopService workshopService,
            ILogger<WorkshopController> logger)
        {
            _workshopService = workshopService;
            _logger = logger;
        }

        /// <summary>
        /// 车间设置首页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("")]
        [Route("Index")]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 编辑页面
        /// </summary>
        /// <param name="id">车间ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("Edit")]
        public async Task<IActionResult> Edit(int? id)
        {
            try
            {
                if (id.HasValue && id.Value > 0)
            {
                var model = await _workshopService.GetWorkshop(id.Value);
                return View(model);
            }
            
            return View(new WorkshopDto());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"加载编辑页面失败：{ex.Message}");
                return View("Error", ex.Message);
            }
        }

        /// <summary>
        /// 获取车间列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetWorkshops")]
        public async Task<IActionResult> GetWorkshops(string code = null, string name = null, bool? isEnable = null, int page = 1, int limit = 10)
        {
            try
            {
                _logger.LogInformation($"接收到获取车间列表请求：code={code}, name={name}, isEnable={isEnable}, page={page}, limit={limit}");
                
                List<WorkshopDto> allData;
                try
                {
                    // 按条件查询
                    if (!string.IsNullOrEmpty(code) || !string.IsNullOrEmpty(name) || isEnable.HasValue)
                    {
                        allData = await _workshopService.GetWorkshopsByCondition(code, name, isEnable);
                    }
                    else
                {
                    allData = await _workshopService.GetWorkshops();
                    }
                }
                catch (Exception serviceEx)
                {
                    _logger.LogError(serviceEx, $"服务层获取车间数据失败：{serviceEx.Message}");
                    return Json(new { code = 1, msg = "获取数据失败：" + serviceEx.Message, count = 0, data = new List<WorkshopDto>() });
                }
                
                // 检查是否有数据
                if (allData == null || !allData.Any())
                {
                    _logger.LogInformation("获取车间列表成功，但无数据");
                    return Json(new { code = 0, msg = "获取成功，但无数据", count = 0, data = new List<WorkshopDto>() });
                }

                // 计算分页数据
                var totalCount = allData.Count;
                var pageData = allData
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToList();

                _logger.LogInformation($"获取车间列表成功，总数：{totalCount}，当前页数据量：{pageData.Count}");
                return Json(new { code = 0, msg = "获取成功", count = totalCount, data = pageData });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取车间列表失败：{ex.Message}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, count = 0, data = new List<WorkshopDto>() });
            }
        }

        /// <summary>
        /// 获取单个车间
        /// </summary>
        /// <param name="id">车间ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetById/{id}")]
        public async Task<IActionResult> GetWorkshop(int id)
        {
            try
            {
                _logger.LogInformation($"接收到获取单个车间请求，ID：{id}");

                if (id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的车间ID", data = new object() });
                }

                var model = await _workshopService.GetWorkshop(id);
                if (model == null)
                {
                    return Json(new { code = 1, msg = $"未找到ID为{id}的车间", data = new object() });
                }

                return Json(new { code = 0, msg = "获取成功", data = model });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取单个车间失败，ID：{id}，错误：{ex.Message}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, data = new object() });
            }
        }

        /// <summary>
        /// 添加车间
        /// </summary>
        /// <param name="input">车间数据</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Add")]
        public async Task<IActionResult> Add([FromBody] CreateUpdateWorkshopDto input)
        {
            try
            {
                _logger.LogInformation($"接收到添加车间请求：Code={input?.Code}, Name={input?.Name}");

                if (input == null)
                {
                    return Json(new { code = 1, msg = "无效的车间数据" });
                }

                var id = await _workshopService.AddWorkshop(input);
                return Json(new { code = 0, msg = "添加成功", id = id });
            }
            catch (ArgumentException argEx)
            {
                _logger.LogWarning(argEx, $"添加车间参数验证失败：{argEx.Message}");
                return Json(new { code = 1, msg = argEx.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加车间失败：{ex.Message}");
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 更新车间
        /// </summary>
        /// <param name="input">车间数据</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Update")]
        public async Task<IActionResult> Update([FromBody] WorkshopDto input)
        {
            try
            {
                _logger.LogInformation($"接收到更新车间请求：ID={input?.Id}, Code={input?.Code}, Name={input?.Name}");

                if (input == null || input.Id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的车间数据或ID" });
                }

                // 转换为创建更新DTO
                var updateDto = new CreateUpdateWorkshopDto
                {
                    Code = input.Code,
                    Name = input.Name,
                    Description = input.Description,
                    IsEnable = input.IsEnable,
                    WorkshopSize = input.WorkshopSize,
                    WorkshopPerson = input.WorkshopPerson
                };

                var id = await _workshopService.UpdateWorkshop(input.Id, updateDto);
                return Json(new { code = 0, msg = "更新成功", id = id });
            }
            catch (ArgumentException argEx)
            {
                _logger.LogWarning(argEx, $"更新车间参数验证失败：{argEx.Message}");
                return Json(new { code = 1, msg = argEx.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新车间失败：{ex.Message}");
                return Json(new { code = 1, msg = "更新失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 删除车间
        /// </summary>
        /// <param name="id">车间ID</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Delete/{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                _logger.LogInformation($"接收到删除车间请求，ID：{id}");

                if (id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的车间ID" });
                }

                await _workshopService.DeleteWorkshop(id);
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除车间失败，ID：{id}，错误：{ex.Message}");
                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 设置车间状态
        /// </summary>
        /// <param name="id">车间ID</param>
        /// <param name="isEnable">启用状态</param>
        /// <returns></returns>
        [HttpPost]
        [Route("SetStatus")]
        public async Task<IActionResult> SetStatus(int id, bool isEnable)
        {
            try
            {
                _logger.LogInformation($"接收到设置车间状态请求，ID：{id}，IsEnable：{isEnable}");

                if (id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的车间ID" });
                }

                var result = await _workshopService.SetWorkshopStatus(id, isEnable);
                if (result)
                {
                    return Json(new { code = 0, msg = $"车间已{(isEnable ? "启用" : "禁用")}" });
                }
                else
                {
                    return Json(new { code = 1, msg = "设置状态失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"设置车间状态失败，ID：{id}，IsEnable：{isEnable}，错误：{ex.Message}");
                return Json(new { code = 1, msg = "设置状态失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 检查车间编码是否存在
        /// </summary>
        /// <param name="code">车间编码</param>
        /// <param name="id">排除的车间ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("CheckCode")]
        public async Task<IActionResult> CheckCode(string code, int? id = null)
        {
            try
            {
                if (string.IsNullOrEmpty(code))
                {
                    return Json(new { exists = false });
                }

                var exists = await _workshopService.IsCodeExist(code, id);
                return Json(new { exists });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"检查车间编码是否存在失败，Code：{code}，错误：{ex.Message}");
                return Json(new { exists = false, error = ex.Message });
            }
        }

        /// <summary>
        /// 获取车间树形结构
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetTree")]
        public async Task<IActionResult> GetWorkshopTree()
        {
            try
            {
                _logger.LogInformation("接收到获取车间树形结构请求");

                var data = await _workshopService.GetWorkshopTree();
                return Json(new { code = 0, msg = "获取成功", data });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取车间树形结构失败：{ex.Message}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, data = new List<WorkshopDto>() });
            }
        }
    }
} 